<template>
    <div class="pwd-box">
        <el-form ref="ruleFormRef" :model="form" label-width="100px"  :rules="rules">
            <el-form-item label="旧密码" prop="oldPwd">
                <el-input v-model="form.oldPwd" placeholder="请输入旧密码" type="password" />
            </el-form-item>
            <el-form-item label="新密码" prop="newPwd">
                <el-input v-model="form.newPwd" placeholder="请输入新密码" type="password" />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPwd">
                <el-input v-model="form.confirmPwd" placeholder="请输入确认密码" type="password" />
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="submitForm(ruleFormRef)">
                    保存
                </el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { reactive ,ref} from 'vue'
const ruleFormRef = ref(null)
const form = reactive({
    oldPwd: '',
    newPwd: '',
    confirmPwd:''
})

const validatePass = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入新密码!'))
    } else {
        if (form.confirmPwd !== '') {
            if (!ruleFormRef.value) return
            ruleFormRef.value.validateField('confirmPwd')
        }
        callback()
    }
}
const validatePass2 = (rule,value, callback) => {
    if (value === '') {
        callback(new Error('请再一次输入密码'))
    } else if (value !== form.newPwd) {
        callback(new Error("两次密码不一致!"))
    } else {
        callback()
    }
}
const rules = reactive({
    newPwd: [{ validator: validatePass, trigger: 'blur' }],
    confirmPwd: [{ validator: validatePass2, trigger: 'blur' }],
    oldPwd: [{ required: true, message: '请输入旧的密码', trigger: 'blur' },],
})

const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            console.log('submit!')
        } else {
            console.log('error submit!')
        }
    })
}
</script >
<style lang="less" scoped>
.pwd-box{
    padding: 20px;
    border:1px solid #ddd;
}
.el-input{
    width: 300px;
}
</style>